package com.nonintrusive.client.tabs.askquestion;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nonintrusive.client.GlobalNonIntrusive;
import com.nonintrusive.client.database.ClientDB;
import com.nonintrusive.client.send.R;
import com.nonintrusive.message.MessageNonIntrusive;

public class AskQuestionActivity extends Activity {

	private static final String TAG = "NonIntrusiveClientSend";
	protected static final String ENCODING = "UTF-8";

	// question
	private ArrayList<EditText> mAnswersListView;
	private int mAnswersNo = 3;
	private String qMessage;
	private String[] qAnswers;
	private String qTags;

	// GUI
	private EditText mQuestion;
	private EditText mTags;
	private Handler mHandler;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ask_question);

		initState();

		loadGui();
	}

	/**
	 * Initiates the GUI elements
	 */
	private void loadGui() {
		mQuestion = (EditText) findViewById(R.id.editTextQuestion);
		mTags = (EditText) findViewById(R.id.editTextTags);

		Button addButton = (Button) findViewById(R.id.buttonAdd);
		addButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mAnswersNo > GlobalNonIntrusive.MAX_ANSWERS) {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(
									AskQuestionActivity.this,
									"You've reached maximum answers per question!",
									Toast.LENGTH_SHORT).show();
						}
					});
					return;
				}
				Context ctx = AskQuestionActivity.this;

				TextView labelA = new TextView(ctx);
				labelA.setText("A" + mAnswersNo++);
				labelA.setLayoutParams(new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

				EditText answerText = new EditText(ctx);
				answerText.setLayoutParams(new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				mAnswersListView.add(answerText);

				LinearLayout layout = new LinearLayout(ctx);
				layout.setOrientation(LinearLayout.HORIZONTAL);

				layout.addView(labelA);
				layout.addView(answerText);

				LinearLayout parent = (LinearLayout) findViewById(R.id.answersLayout);
				parent.addView(layout, new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			}
		});

		Button sendButton = (Button) findViewById(R.id.buttonSend);
		sendButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				sendQToServer();
			}
		});

		Button clearButton = (Button) findViewById(R.id.clearForm);
		clearButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mQuestion.setText("");
				mTags.setText("");
				for (EditText answer : mAnswersListView) {
					answer.setText("");
				}
			}
		});
	}

	/**
	 * Load the initial state
	 */
	private void initState() {
		mHandler = new Handler();
		mAnswersListView = new ArrayList<EditText>();
		mAnswersListView.add((EditText) findViewById(R.id.editTextA1));
		mAnswersListView.add((EditText) findViewById(R.id.editTextA2));
		qAnswers = new String[GlobalNonIntrusive.MAX_ANSWERS];
	}

	/**
	 * Builds the message to send to server
	 * 
	 * @return message for server
	 */
	private MessageNonIntrusive buildMessage() {
		MessageNonIntrusive message = new MessageNonIntrusive();
		synchronized (GlobalNonIntrusive.clientID) {
			message.senderId = GlobalNonIntrusive.clientID;
			System.out.println("id ssss" + message.senderId);
		}
		message.type = MessageNonIntrusive.ASK_QUESTION;
		synchronized (GlobalNonIntrusive.clientID) {
			message.senderId = GlobalNonIntrusive.clientID;
		}

		message.content = mQuestion.getText().toString();

		int size = mAnswersListView.size();
		int k = 0;
		for (int i = 0; i < size; i++) {
			EditText editText = mAnswersListView.get(i - k);
			String textA = editText.getText().toString();
			if (textA.equals("")) {
				k++;
				continue;
			}
			qAnswers[i - k] = textA;

			message.answers.add(textA);
		}

		for (int i = message.answers.size(); i < 5; i++) {
			message.answers.add("");
		}
		
		for (int i = 0; i < 5; i++) {
			message.nrAnswers.add(0);
		}
		
		
	/*	qTags = "";
		String[] tags = mTags.getText().toString().split(" ");
		size = tags.length;
		for (int i = 0; i < size; i++) {
			qTags += tags[i] + " ";
		}
		message.tags = qTags;
    */
		message.tags = mTags.getText().toString();
		
		Log.d(TAG, "message " + message);

		return message;
	}

	/**
	 * Sends the message to server
	 * 
	 * @param message
	 */
	private void sendQToServer() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				boolean success = false;
				int qId = -1;
				MessageNonIntrusive message = buildMessage();
				// TODO: add clear button; save last unsended question
				try {
					Socket socket = new Socket(GlobalNonIntrusive.SERVER_IP,
							GlobalNonIntrusive.PORT);
					ObjectOutputStream oos = new ObjectOutputStream(
							socket.getOutputStream());
					oos.writeObject(message);
					ObjectInputStream ois = new ObjectInputStream(
							socket.getInputStream());
					message = (MessageNonIntrusive) ois.readObject();
					//message.type = MessageNonIntrusive.QUESTION_ID;
					qId = Integer.parseInt(message.content);
					oos.close();
					ois.close();
					socket.close();
					success = true;
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				
				if (success)
					addQuestionToDB(qId);
			}
		}).start();
	}

	/**
	 * It should be called only after buildMessage()
	 * @param qId 
	 */
	private void addQuestionToDB(int qId) {
		if (qMessage == null || qMessage.equals(""))
			return;
		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		values.put(ClientDB.QUESTION_ID, qId);
		values.put(ClientDB.MESSAGE, qMessage);
		values.put(ClientDB.ANSWER1, qAnswers[0]);
		values.put(ClientDB.ANSWER2, qAnswers[1]);
		if (qAnswers[2] != null) {
			values.put(ClientDB.ANSWER3, qAnswers[2]);
			if (qAnswers[3] != null) {
				values.put(ClientDB.ANSWER4, qAnswers[3]);
				if (qAnswers[4] != null)
					values.put(ClientDB.ANSWER5, qAnswers[4]);
			}
		}
		values.put(ClientDB.TAGS, qTags);
		values.put(ClientDB.IS_MY_QUESTION, true);
		values.put(ClientDB.TIMESTAMP, System.currentTimeMillis());
		cr.insert(ClientDB.CONTENT_URI, values);
	}
}